package com.luyou.framework.mybatis.handle;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import org.apache.commons.lang3.StringUtils;


/**
 * 动态表名后缀
 * @author luyou
 * @version 1.0
 * Create by 2024-6-29 15:53:17
 */
public class LuyouTableNameHandler implements TableNameHandler {

    private static final  InheritableThreadLocal<String> TABLE_SUFFIX = new InheritableThreadLocal<>();

    public static void setTableSuffix(String suffixStr){
        TABLE_SUFFIX.set(suffixStr);
    }

    public static void remove(){
        TABLE_SUFFIX.remove();
    }

    @Override
    public String dynamicTableName(String sql, String tableName) {
        String suffixStr = TABLE_SUFFIX.get();
        if (StringUtils.isNotBlank(suffixStr)) {
            if (tableName.endsWith("`")) {
                tableName = StringUtils.substring(tableName, 0, tableName.length() - 1) + "_" + suffixStr + "`";
            } else {
                tableName = tableName + "_" + suffixStr;
            }
        }
        return tableName;
    }
}
